package com.project.srtp.secure.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.*;

@Component
@Slf4j
public class JwtTokenProvider {
    @Getter
    private final long validityInMilliseconds;

    private final Key key;

    public JwtTokenProvider(
            @Value("${spring.security.jwt.secret}") String secret,
            @Value("${spring.security.jwt.expiration}") long validityInSeconds) {

        byte[] keyBytes = Base64.getEncoder().encode(secret.getBytes());
        this.key = Keys.hmacShaKeyFor(keyBytes);
        this.validityInMilliseconds = validityInSeconds * 1000;
    }

    /**
     * 通用生成 Token 方法，支持添加角色等 claims
     */
    public String generateToken(String username, List<String> roles) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("roles", roles);
        return createToken(username, claims);
    }


    /**
     * 重载：无角色
     */
    public String generateToken(UserDetails userDetails) {
        return generateToken(userDetails.getUsername(), Collections.emptyList());
    }

    /**
     * 重载：只使用用户名
     */
    public String generateToken(String username) {
        return createToken(username, Collections.emptyMap());
    }

    /*
     * 重载： 用户id, 用户名
     * */

    public String generateToken(Long userId, String username, List<String> roles) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("roles", roles);
        claims.put("username", username);
        claims.put("userId", userId);
        return createToken(username, claims);
    }


    /**
     * 创建 Token 的底层方法
     */
    private String createToken(String username, Map<String, Object> extraClaims) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + validityInMilliseconds);

        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .addClaims(extraClaims)
                .signWith(key, SignatureAlgorithm.HS512)
                .compact();
    }

    /**
     * 校验 JWT Token 是否合法与未过期
     */
    public boolean validateToken(String token) {
        try {
            Jws<Claims> claims = parseToken(token);
            return !claims.getBody().getExpiration().before(new Date());
        } catch (JwtException | IllegalArgumentException e) {
            log.error("Invalid JWT token: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 从 token 中获取用户名
     */
    public String getUsernameFromToken(String token) {
        return parseToken(token).getBody().getSubject();
    }

    /**
     * 从 token 中获取角色列表
     */
    public List<String> getRolesFromToken(String token) {
        Claims claims = parseToken(token).getBody();
        Object roles = claims.get("roles");
        if (roles instanceof List<?>) {
            return (List<String>) roles;
        }
        return Collections.emptyList();
    }

    /**
     * 从 token 中获取 userId（可选扩展）
     */
    public Long getUserIdFromToken(String token) {
        return parseToken(token).getBody().get("userId", Long.class);
    }

    /**
     * 安全解析 Token
     */
    private Jws<Claims> parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token);
    }
}
